<template>
	<view>
		<u-gap height="16rpx" bgColor="#F6F6F6" />
		<view class="form">
			<u-form labelPosition="left" :model="model" errorType="toast" :rules="rules" ref="form"
				:labelStyle="labelStyle" labelWidth="160rpx">
				<u-form-item label="优惠券类型" prop="favorableType" borderBottom @click="showSex = true" :customStyle="formItemCustomStyle2">
					<u--input placeholder="请选择类型" inputAlign="right" fontSize="28rpx" clearable maxlength="30"
						placeholderClass="placeHolder" :customStyle="customInputStyle" v-model="model.favorableType"
						disabled disabledColor="#ffffff" />
					<u-icon slot="right" name="arrow-right" />
				</u-form-item>
				
				<u-form-item label="优惠券名称" :customStyle="formItemCustomStyle2" borderBottom prop="favorableTitle">
					<u-input placeholder="请输入优惠券名称" inputAlign="right" fontSize="28rpx" clearable maxlength="30"
						placeholderClass="placeHolder" :customStyle="customInputStyle" v-model="model.favorableTitle" />
				</u-form-item>
				
				<u-form-item label="优惠券面值（元）" :customStyle="formItemCustomStyle2" borderBottom prop="favorableFaceValue"
					labelWidth="140">
					<u-input placeholder="请输入优惠券面值" inputAlign="right" fontSize="28rpx" clearable maxlength="30"
						placeholderClass="placeHolder" :customStyle="customInputStyle" v-model="model.favorableFaceValue" />
				</u-form-item>
				
				<u-form-item label="优惠券发放总数" labelWidth="140" :customStyle="formItemCustomStyle2" borderBottom
					prop="favorableNum">
					<u-input placeholder="请输入优惠券发放总数" inputAlign="right" fontSize="28rpx" clearable maxlength="30"
						placeholderClass="placeHolder" :customStyle="customInputStyle" v-model="model.favorableNum" />
				</u-form-item>
				
				<u-form-item label="使用规则" labelWidth="140" :customStyle="formItemCustomStyle2" borderBottom prop="favorableDescription"
					labelPosition="bottom">
					<u-textarea ref="textareaName" v-model="model.favorableDescription" :customStyle="textAreaCustomStyle"
						placeholder="请输入优惠券使用规则" fixed maxlength="200" autoHeight />
				</u-form-item>

				<u-form-item label="优惠券使用起始时间" :customStyle="formItemCustomStyle" borderBottom prop="useTimeBegin"
					labelWidth="140">
					<u-datetime-picker ref="datetimePicker" :show="pickerShow" mode="date" v-model="model.useTimeBegin"
						@confirm="startTimeChange" @cancel="pickerShow = false"></u-datetime-picker>

					<u-text align="right" :iconStyle="iconStyle" @click="pickerShow = true" color="#666" size="28rpx"
						suffixIcon="arrow-right" :text="model.useTimeBegin1 ? model.useTimeBegin1 : '请选择开始时间' " />
				</u-form-item>

				<u-form-item label="优惠券使用结束时间" :customStyle="formItemCustomStyle" borderBottom prop="useTimeEnd"
					:clearIcon="false" labelWidth="140">
					<u-datetime-picker ref="datetimePicker2" :show="pickerShow2" mode="date" v-model="model.useTimeEnd"
						@confirm="endTimeChange" @cancel="pickerShow2 = false"></u-datetime-picker>
					<u-text align="right" :iconStyle="iconStyle" color="#666" size="28rpx" suffixIcon="arrow-right"
						@click="pickerShow2 = true" :text="
                            model.useTimeEnd1
                                ? model.useTimeEnd1
                                : '请选择结束时间'
                        " />
				</u-form-item>
				
				<u-form-item label="关联商品" borderBottom ref="item1"  prop="goodsIdSet"
					:customStyle="formItemCustomStyle2"  @click="chooseGoods()">
					<!-- <u--input placeholder="请选择商品" inputAlign="right" fontSize="28rpx" clearable maxlength="30"
						placeholderClass="placeHolder" :customStyle="customInputStyle" v-model="goodNum.length"
						disabled disabledColor="#ffffff" /> -->
					<u-icon :label="goodNum.length ? ('已关联'+ goodNum.length +'款商品') :  '请选择商品'" labelPos="left" slot="right" name="arrow-right" />
				</u-form-item>
				
				<u-form-item label="限领一张" labelWidth="140" :customStyle="formItemCustomStyle2" borderBottom >
					<view style="display: flex;justify-content: flex-end;">
						<u-switch v-model="model.favorableLimit" @change="change" />
					</view>
				</u-form-item>
			</u-form>
			<u-action-sheet :show="showSex" :actions="couponType" title="请选择类型" @close="showSex = false"
				@select="favorableSelect">
			</u-action-sheet>
		</view>
		<view class="bottomFrom"><u-button :text="type == '编辑' ? '确定' : '创建'" shape="circle" :hairline="false" :loading="loading"
				:customStyle="buttonCustomStyle" @click="submit" /></view>
	</view>
</template>

<script>
	import {
		selectSalesMan,
		createMeet
	} from "@/api/salesmanMeeting.js";
	import { createCoupon,createCouponDetail,updateCoupon} from "@/api/order.js";
	import {
		mapGetters
	} from "vuex";
	import { numDiv, numMulti } from "@/js_sdk/nl-precisionNum/precisionNum.js";
	import moment from "moment";
	const dayStart = moment(
	    new Date(new Date(new Date().toLocaleDateString()).getTime())
	);
	const dataEnd = moment(
	    new Date(
	        new Date(new Date().toLocaleDateString()).getTime() +
	            24 * 60 * 60 * 1000 -
	            1
	    )
	);
	export default {
		computed: {
			...mapGetters(["userInfo"]),
		},
		data() {
			return {
				goodNum:'',
				type:'',
				favorableId:'',
				showSex: false,
				couponType: [{
						name: '现金券',
					},
					{
						name: '线下券',
					},
				],
				pickerShow: false,
				pickerShow2: false,
				loading: false,
				startPicker: "",
				confirmButtonCustomstyle: {
					border: "none",
					height: "52rpx",
				},
				buttonCustomStyle: {
					color: "#FFF",
					backgroundColor: "#588BF3",
				},
				textAreaCustomStyle: {
					marginTop: '24rpx',
					backgroundColor: "#F3F3F3 ",
					color: "#606266 ",
					width: "100%",
					padding: "20rpx",
					boxSizing: "border-box",
					fontSize: "28rpx",
					borderRadius: '16rpx',
					border: 'none'
				},
				labelStyle: {
					fontSize: "28rpx",
					color: "#333",
					fontWeight: "bold",
				},
				formItemCustomStyle: {
					padding: "32rpx",
				},
				formItemCustomStyle2: {
					padding: "28rpx 32rpx",
				},
				customInputStyle: {
					padding: '0',
					border: 'none'
				},
				iconStyle: "fontSize:28rpx",
				model: {
					
					favorableType:'',//优惠券类型;1:代金券,2:线下券
					favorableTitle: "", //优惠券标题
					favorableFaceValue:'',//优惠券面值(金额：分)
					favorableNum:'',//优惠券总数,0无限制
					favorableDescription:'',//优惠券描述
					useTimeBegin:dayStart,//优惠券可使用开始时间
					useTimeEnd:dataEnd,//优惠券可使用结束时间
					useTimeBegin1:'',//优惠券可使用开始时间
					useTimeEnd1:'',//优惠券可使用结束时间
					goodsIdSet:[],//商品
					favorableLimit:0,//每人限领数量，默认1，0不限制
				},
				rules: {
					favorableType: [{
						required: true,
						message: "请选择类型"
					}],
					favorableTitle: [{
						required: true,
						message: "请输入优惠券名称"
					}, ],
					favorableFaceValue: [{
						required: true,
						message: "请输入优惠券面额"
					}, ],
					favorableNum: [{
						required: true,
						message: "请输入优惠券数量"
					}],
					favorableDescription: [{
						required: true,
						message: "请输入优惠券使用规则"
					}],
					useTimeBegin: [{
						required: true,
						message: "请输入优惠券启用时间"
					}],
					useTimeEnd: [{
						required: true,
						message: "请输入优惠券结束时间"
					}],
					goodsIdSet: [{
						required: true,
						message: "请选择关联商品"
					}],
				},
			};
		},
		onReady() {
			this.$refs.form.setRules(this.rules);
			// 微信小程序需要用此写法
			this.$refs.datetimePicker.setFormatter(this.formatter);
			this.$refs.datetimePicker2.setFormatter(this.formatter);
		},
		onShow() {
			let that = this
			uni.$on('getuser',function(data){
				that.model.goodsIdSet = data
				that.goodNum = that.model.goodsIdSet
				console.log(that.model.goodsIdSet,'创建页面',that.goodNum.length);
			})
		},
		created() {
			this.startPicker = Date.now();
		},
		onLoad(options) {
			this.type = options.type || ''
			uni.setNavigationBarTitle({
				title: this.type == '编辑' ? '编辑优惠券' : '创建优惠券',
			});
			if (this.type == '编辑') {
				this.favorableId = options.id
			    createCouponDetail(this.favorableId).then((res) => {
			        if (res.code == 200) {
			           this.model = res.data
					   this.model.useTimeBegin1= uni.$u.timeFormat(this.model.useTimeBegin, 'yyyy-mm-dd ');
					   this.model.useTimeEnd1= uni.$u.timeFormat(this.model.useTimeEnd, 'yyyy-mm-dd ');
					   this.model.goodsIdSet= this.model.goodsIdSet.split(',');
					   this.model.favorableFaceValue= this.model.favorableFaceValue ? numDiv(this.model.favorableFaceValue, 100) : 0
					   this.goodNum = this.model.goodsIdSet;
					   this.model.favorableLimit= this.model.favorableLimit ? true : false
					   this.model.favorableType= this.model.favorableType == '1' ? '现金券' : '线下券'
			        }
			    });
			}
		},
		methods: {
			chooseGoods(){
				this.$u.route({
					url: "/pages_coupon/shopEdit/index",
					params: {
						couponId:this.favorableId,
						leftValue :JSON.stringify(this.model.goodsIdSet) ,
					},
				});
			},
			favorableSelect(e) {
				this.model.favorableType = e.name
			},
			change(e) {
				console.log('change', e);
				this.model.favorableLimit = e 
			},
			formatter(type, value) {
				if (type === "year") {
					return `${value}年`;
				}
				if (type === "month") {
					return `${value}月`;
				}
				if (type === "day") {
					return `${value}日`;
				}
				return value;
			},
			submit() {
				this.loading = true;
				const that = this;
				this.$refs.form
					.validate()
					.then((res) => {
						const params = {
							favorableType:that.model.favorableType == '现金券' ? '1' :'2',//优惠券类型;1:现金券,2:线下券
							favorableTitle: that.model.favorableTitle, //优惠券标题
							favorableFaceValue: numMulti(that.model.favorableFaceValue, 100),//优惠券面值(金额：分)
							favorableNum:that.model.favorableNum,//优惠券总数,0无限制
							favorableDescription:that.model.favorableDescription,//优惠券描述
							useTimeBegin:that.model.useTimeBegin1 ? (that.model.useTimeBegin1+ " 00:00:00") : '',//优惠券可使用开始时间
							useTimeEnd:that.model.useTimeEnd1 ? (that.model.useTimeEnd1+ " 23:59:59") : '',//优惠券可使用结束时间
							goodsIdSet:that.model.goodsIdSet || [],//商品
							favorableLimit:that.model.favorableLimit ? '1' :'0',//每人限领数量，默认1，0不限制
						};
						console.log(params,'pa>>>')
						if (this.type !== "编辑") {
							createCoupon(params).then((res) => {
								uni.$u.toast("提交成功");
								uni.$u.route({
									type: "reLaunch",
									url: "pages_coupon/coupon_management/index",
								});
							});
							return;
						} else {
							//  修改
							params.id = this.favorableId;
							updateCoupon(params).then((res) => {
								uni.$u.toast("修改成功");
								uni.$u.route({
									type: "reLaunch",
									url: "pages_coupon/coupon_management/index",
								});
							});
						}
						
					})
					.finally(() => {
						that.loading = false;
					});
			},
			startTimeChange(e) {
				const time =
					typeof e.value === "number" ? e.value : Date.parse(e.value);
				this.model.useTimeBegin1 = moment(time).format(
					"YYYY-MM-DD"
				);
				console.log(time,this.model.useTimeBegin)
				this.pickerShow = false;
			},
			endTimeChange(e) {
				const time =
					typeof e.value === "number" ? e.value : Date.parse(e.value);
				this.model.useTimeEnd1 = moment(time).format(
					"YYYY-MM-DD"
				);
				this.pickerShow2 = false;
			},
		},
	};
</script>

<style>
	page {
		background-color: #F6F6F6 !important;
	}
</style>

<style lang="scss" scoped>
	.form {
		background-color: #fff;
	}

	::v-deep.placeHolder {
		color: #666 !important;
		font-size: 28upx !important;
	}

	.radioGroupBox {
		display: flex;
		align-items: center;
	}

	.customClass {
		::v-deep.u-form-item__body {
			flex-direction: column !important;
		}

		.chooseList {
			margin-top: 30upx;
			display: flex;
			flex-wrap: wrap;
			justify-content: flex-start;
			margin-right: 20rpx;
		}
	}

	.scopeList {
		width: 100%;
		height: 80upx;
		align-items: center;
		border-bottom: 1px solid #f3f3f3;

		.scopeLable {
			font-size: 28rpx;
			color: #666;
		}

		.activeColor {
			color: #588bf3;
		}
	}

	.scopeList:first-of-type {
		height: auto;
		padding-bottom: 20upx;
	}

	.scopeList:last-of-type {
		border-bottom: none;
	}

	.indexBox {
		width: 100vw;
		display: flex;
		flex-direction: column;

		&_confirmBox {
			width: 100%;
			height: 90rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 0 20rpx;
			box-sizing: border-box;
			border-bottom: 1px solid #f0e5e6;
		}

		&_indexList {
			width: 100%;
			height: calc(100% - 90rpx);
		}
	}

	.bottomFrom {
		width: 750rpx;
		background: #FFFFFF;
		box-shadow: 0rpx -4rpx 6rpx 0rpx rgba(0, 0, 0, 0.08);
		position: fixed;
		bottom: 0;
		padding: 20rpx 40rpx 60rpx;
	}
</style>